<template>
  <div style="margin: 20px; margin-top: 60px;">
    <ContentWrap>
      <!-- 搜索工作栏 -->
      <el-form
        class="-mb-15px"
        :model="queryParams"
        ref="queryFormRef"
        :inline="true"
        label-width="auto"
      >
<!--        <el-form-item :label="t('searchbar.WellCode')" prop="wellCode">
          <el-input
            v-model="queryParams.wellCode"
            :placeholder="t('searchbar.WellCodeInfo')"
            clearable
            @keyup.enter="handleQuery"
            class="!w-240px"
          />
        </el-form-item>-->



        <el-form-item :label="t('searchbar.wellType')" prop="wellType">
          <el-select
            v-model="queryParams.wellType"
            :placeholder="t('searchbar.wellTypeInfo')"
            clearable
            class="!w-240px"
          >
            <el-option
              v-for="dict in getStrDictOptions(DICT_TYPE.WELL_TYPE)"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item :label="t('searchbar.wellCategory')" prop="wellCategory">
          <el-select
            v-model="queryParams.wellCategory"
            :placeholder="t('searchbar.wellCategoryInfo')"
            clearable
            class="!w-240px"
          >
            <el-option
              v-for="dict in getStrDictOptions(DICT_TYPE.WELL_CATEGORY)"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>


        <el-form-item :label="t('searchbar.oilFieldBlock')" prop="oilFieldBlock">
          <el-select
            v-model="queryParams.oilFieldBlock"
            :placeholder="t('searchbar.oilFieldBlockInfo')"
            clearable
            class="!w-240px"
          >
            <el-option
              v-for="dict in getStrDictOptions(DICT_TYPE.BLOCK)"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item :label="t('searchbar.wellName')" prop="wellName">
          <el-input
            v-model="queryParams.wellName"
            :placeholder="t('searchbar.wellNameInput')"
            clearable
            @keyup.enter="handleQuery"
            class="!w-240px"
          />
        </el-form-item>
        <!--        <el-form-item :label="t('searchbar.wellId')" prop="wellId">
                  <el-input
                    v-model="queryParams.wellId"
                    :placeholder="t('searchbar.wellIdInfo')"
                    clearable
                    @keyup.enter="handleQuery"
                    class="!w-240px"
                  />
                </el-form-item>-->


        <!--      <el-form-item :label="t('searchbar.state')" prop="state">
        <el-select
          v-model="queryParams.state"
          class="!w-240px"
          clearable
          :placeholder="t('searchbar.stateInfo')"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.DEVICE_STATE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>-->


        <el-form-item :label="t('searchbar.drillingDate')" prop="drillingDate">
          <el-date-picker
            v-model="queryParams.drillingDate"
            value-format="YYYY-MM-DD HH:mm:ss"
            type="daterange"
            :start-placeholder="t('searchbar.startDate')"
            :end-placeholder="t('searchbar.endDate')"
            :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
            class="!w-240px"
          />
        </el-form-item>


        <!--
                <el-form-item :label="t('searchbar.createTime')" prop="createTime">
                  <el-date-picker
                    v-model="queryParams.createTime"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    type="datetimerange"
                    :start-placeholder="t('searchbar.startDate')"
                    :end-placeholder="t('searchbar.endDate')"
                    :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
                    class="!w-240px"
                  />
                </el-form-item>
        -->

        <el-form-item>
          <el-button @click="handleQuery">
            <Icon icon="ep:search" class="mr-5px" /> {{ t('action.search') }}
          </el-button>
          <el-button @click="resetQuery">
            <Icon icon="ep:refresh" class="mr-5px" /> {{ t('action.reset') }}
          </el-button>
          <el-button
            type="primary"
            plain
            @click="openAddForm('create')"
            v-hasPermi="['base:site:create']"
          >
            <Icon icon="ep:plus" class="mr-5px" /> {{ t('action.create') }}
          </el-button>
          <!--        <el-button
        type="success"
        plain
        @click="handleExport"
        :loading="exportLoading"
        v-hasPermi="['base:site:export']"
      >
        <Icon icon="ep:download" class="mr-5px" /> {{ t('action.export') }}
      </el-button>-->
        </el-form-item>
      </el-form>
    </ContentWrap>

    <!-- 列表 -->
    <ContentWrap>
      <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
<!--        <el-table-column :label="t('formData.WellCode')" align="center" prop="wellCode" />-->
<!--        <el-table-column :label="t('formData.wellId')" align="center" prop="wellId" />-->
<!--        <el-table-column :label="t('formData.wellsource')" align="center" prop="wellSource">-->
<!--          <template #default="scope">-->
<!--            <dict-tag :type="DICT_TYPE.WELL_SOURCE" :value="scope.row.wellSource" />-->
<!--          </template>-->
<!--        </el-table-column>-->
        <el-table-column :label="t('formData.wellName')" align="center" prop="wellName" />
        <el-table-column :label="t('formData.wellType')" align="center" prop="wellType">
          <template #default="scope">
            <dict-tag :type="DICT_TYPE.WELL_TYPE" :value="scope.row.wellType" />
          </template>
        </el-table-column>
        <el-table-column :label="t('formData.wellCategory')" align="center" prop="wellCategory">
          <template #default="scope">
            <dict-tag :type="DICT_TYPE.WELL_CATEGORY" :value="scope.row.wellCategory" />
          </template>
        </el-table-column>
        <el-table-column :label="t('formData.oilField')" align="center" prop="oilField" />
        <el-table-column :label="t('formData.oilFieldBlock')" align="center" prop="oilFieldBlock">
          <template #default="scope">
            <dict-tag :type="DICT_TYPE.BLOCK" :value="scope.row.oilFieldBlock" />
          </template>
        </el-table-column>
        <el-table-column :label="t('formData.location')" align="center">
          <template #default="scope">
            {{ address.find((user) => user.id === Number(scope.row.province))?.name }}
            {{
              address
                .find((user) => user.id === Number(scope.row.province))
                ?.children.find((users) => users.id === Number(scope.row.city))?.name
            }}
            {{
              address
                .find((user) => user.id === Number(scope.row.province))
                ?.children.find((users) => users.id === Number(scope.row.city))
                ?.children.find((userss) => userss.id === Number(scope.row.county))?.name
            }}
          </template>
        </el-table-column>

<!--        <el-table-column :label="t('formData.LongitudeLatitude')" align="center">-->
<!--          <template #default="scope">-->
<!--            {{ scope.row.longitude }}, {{ scope.row.latitude }}-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--        <el-table-column :label="t('formData.aimLayer')" align="center" prop="aimLayer" />-->
<!--        <el-table-column-->
<!--          :label="t('formData.drillingWellde')"-->
<!--          align="center"-->
<!--          prop="drillingWellde"-->
<!--        />-->
<!--        <el-table-column :label="t('formData.drillingLayer')" align="center" prop="drillingLayer" />-->
<!--        <el-table-column-->
<!--          :label="t('formData.welldeLithology')"-->
<!--          align="center"-->
<!--          prop="welldeLithology"-->
<!--        >-->
<!--          <template #default="scope">-->
<!--            <dict-tag :type="DICT_TYPE.LITHOLOGY_STANDARD" :value="scope.row.welldeLithology" />-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--        <el-table-column-->
<!--          :label="t('formData.projectProfile')"-->
<!--          align="center"-->
<!--          prop="projectProfile"-->
<!--        />-->

        <el-table-column
          :label="t('formData.drillingDate')"
          align="center"
          prop="drillingDate"
          :formatter="dateFormatter2"
          width="180px"
        />
        <el-table-column :label="t('formData.designWellde')" align="center" prop="designWellde" />
        <el-table-column :label="t('formData.contactPerson')" align="center" prop="contactPerson" />
        <el-table-column :label="t('formData.contactPhone')" align="center" prop="contactPhone" />
        <el-table-column :label="t('formData.remark')" align="center" prop="remark" />
        <el-table-column :label="t('formData.state')" align="center" prop="state">
          <template #default="scope">
            <el-tag :type="scope.row.state ? 'success' : 'danger'">
              {{ scope.row.state ? t('action.abled') : t('action.disabled') }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          :label="t('formData.createTime')"
          align="center"
          prop="createTime"
          :formatter="dateFormatter"
          width="180px"
        />

        <el-table-column :label="t('formData.operate')" align="center" fixed="right" width="180px">
          <template #default="scope">
            <el-button
              v-if="scope.row.state == false"
              link
              type="primary"
              @click="openUpdateForm('update', scope.row.wellCode)"
              v-hasPermi="['base:site:update']"
            >
              {{ t('action.edit') }}
            </el-button>

            <el-button
              v-if="scope.row.state"
              link
              type="danger"
              @click="handleDisable(scope.row.wellCode)"
              v-hasPermi="['base:site:update']"
            >
              {{ t('action.disabled') }}
            </el-button>

            <el-button
              v-else
              link
              type="success"
              @click="handleEnable(scope.row.wellCode)"
              v-hasPermi="['base:site:update']"
            >
              {{ t('action.abled') }}
            </el-button>

            <el-button
              link
              type="danger"
              @click="handleDelete(scope.row.wellCode)"
              v-hasPermi="['base:site:delete']"
            >
              {{ t('action.delete') }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <Pagination
        :total="total"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </ContentWrap>
  </div>
  <!-- 表单弹窗：添加/修改 -->
  <SiteForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { getStrDictOptions, DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { dateFormatter, dateFormatter2 } from '@/utils/formatTime'
import download from '@/utils/download'
import { SiteApi, SiteVO } from '@/api/base/site'
import SiteForm from './SiteForm.vue'

/** 现场 列表 */
defineOptions({ name: 'Site' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<SiteVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  wellId: undefined,
  wellCode: undefined,
  wellName: undefined,
  wellType: undefined,
  wellCategory: undefined,
  oilField: undefined,
  oilFieldBlock: undefined,
  state: undefined,
  drillingDate: [],
  createTime: []
})
const address = ref([])
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await SiteApi.getSitePage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}


const formRef = ref()
/** 添加操作 */
const openAddForm = async (type: string, wellCode?: string) => {
  formRef.value.open(type, wellCode)
}

/** 修改操作 */
const openUpdateForm = (type: string, wellCode?: string) => {
  formRef.value.open(type, wellCode)
}

/** 启用按钮操作 */
const handleEnable = async (wellCode: string) => {
  const enbleWellNum = await SiteApi.getWellNum();
  console.log(enbleWellNum);
  if (enbleWellNum < 1 ){
    try {
      // 启用的二次确认
      await message.enableConfirm()
      // 发起启用
      await SiteApi.enable(wellCode)
      message.success(t(t('action.abledSuccess')))
      // 刷新列表
      await getList()
    } catch {}
  }else {
    await message.alertWarning("现场只能启用一个井！")
  }
}

/** 禁用按钮操作 */
const handleDisable = async (wellCode: string) => {
  try {
    // 禁用的二次确认
    await message.disableConfirm()
    // 发起禁用
    await SiteApi.disable(wellCode)
    message.success(t(t('action.disabledSuccess')))
    // 刷新列表
    await getList()
  } catch {}
}

/** 删除按钮操作 */
const handleDelete = async (wellCode: string) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await SiteApi.deleteSite(wellCode)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await SiteApi.exportSite(queryParams)
    download.excel(data, '现场.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(async () => {
  address.value = await SiteApi.getAreatest()
  getList()
})

const testArea = async () => {
  const data = await SiteApi.getAreatest()
  console.log(data)
}
</script>



